<template>
  <div class="admin-projects">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="项目名称">
          <el-input v-model="searchForm.title" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="组织名称">
          <el-input v-model="searchForm.organizationId" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.auditStatus" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="projectList" border stripe v-loading="tableLoading" style="width: 100%;">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="项目名称" min-width="200">
          <template #default="{ row }">
            <div class="project-name">
              <el-image
                :src="row.image"
                :preview-src-list="[row.image]"
                fit="cover"
                class="project-cover"
              />
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="organizationName" label="所属组织" width="150" />
        <el-table-column prop="location" label="活动地点" width="150" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.auditStatus)">
              {{ getStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.auditStatus === 0"
              link 
              type="primary" 
              @click="handleApprove(row)"
            >通过</el-button>
            <el-button 
              v-if="row.auditStatus === 0"
              link 
              type="danger" 
              @click="handleReject(row)"
            >拒绝</el-button>
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="项目详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="项目名称" :span="2">{{ currentDetail.title }}</el-descriptions-item>
        <el-descriptions-item label="所属组织" :span="2">{{ currentDetail.organizationId }}</el-descriptions-item>
        <el-descriptions-item label="项目封面" :span="2">
          <el-image
            :src="currentDetail.image"
            :preview-src-list="[currentDetail.image]"
            fit="cover"
            class="detail-cover"
          />
        </el-descriptions-item>
        <el-descriptions-item label="活动时间">{{ formatDate(currentDetail.date) }}</el-descriptions-item>
        <el-descriptions-item label="活动地点">{{ currentDetail.location }}</el-descriptions-item>
        <el-descriptions-item label="详细地址" :span="2">{{ currentDetail.fullAddress }}</el-descriptions-item>
        <el-descriptions-item label="参与人数">
          {{ currentDetail.currentParticipants }}/{{ currentDetail.maxParticipants }}
        </el-descriptions-item>
        <el-descriptions-item label="活动时长">{{ currentDetail.duration }} 分钟</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDetail.auditStatus)">
            {{ getStatusText(currentDetail.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(currentDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item v-if="currentDetail.rejectReason" label="拒绝原因" :span="2">{{ currentDetail.rejectReason }}</el-descriptions-item>
        <el-descriptions-item label="项目描述" :span="2">{{ currentDetail.description }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProjectList, getProjectDetail, approveProject, rejectProject } from '@/api/project'

// 搜索表单
const searchForm = reactive({
  title: '',
  organizationId: '',
  auditStatus: '',
  dateRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 项目列表
const projectList = ref([])
const tableLoading = ref(false)
const dataInitialized = ref(false)

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref({})

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',   // 待审核
    1: 'success',   // 已通过
    2: 'danger'     // 已拒绝
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return texts[status] || '未知'
}

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
}

// 获取项目列表
const loadProjectList = async () => {
  tableLoading.value = true
  dataInitialized.value = false
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      title: searchForm.title || undefined,
      organizationId: searchForm.organizationId || undefined,
      auditStatus: searchForm.auditStatus === '' ? undefined : searchForm.auditStatus,
      startTime: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endTime: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    }
    
    const res = await getProjectList(params)
    if (res && res.code === 200) {
      projectList.value = res.data.list
      total.value = res.data.total
      
      setTimeout(() => {
        dataInitialized.value = true
      }, 100)
    } else {
      ElMessage.error(res?.message || '获取项目列表失败')
    }
  } catch (error) {
    console.error('加载项目列表出错:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 查看详情
const handleDetail = async (row) => {
  try {
    const res = await getProjectDetail(row.id)
    if (res && res.code === 200) {
      currentDetail.value = res.data
      nextTick(() => {
        detailDialogVisible.value = true
      })
    } else {
      ElMessage.error(res?.message || '获取项目详情失败')
    }
  } catch (error) {
    console.error('获取项目详情出错:', error)
    ElMessage.error('获取项目详情失败')
  }
}

// 处理审核通过
const handleApprove = (row) => {
  ElMessageBox.confirm(
    '确认通过该项目？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await approveProject(row.id)
      if (res && res.code === 200) {
        ElMessage.success('审核通过成功')
        loadProjectList()
      } else {
        ElMessage.error(res?.message || '审核操作失败')
      }
    } catch (error) {
      console.error('审核项目出错:', error)
      ElMessage.error('审核操作失败，请重试')
    }
  }).catch(() => {})
}

// 处理审核拒绝
const handleReject = (row) => {
  ElMessageBox.prompt('请输入拒绝原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入拒绝原因'
  }).then(async ({ value }) => {
    try {
      const res = await rejectProject(row.id, value)
      if (res && res.code === 200) {
        ElMessage.success('已拒绝该项目')
        loadProjectList()
      } else {
        ElMessage.error(res?.message || '拒绝操作失败')
      }
    } catch (error) {
      console.error('拒绝项目出错:', error)
      ElMessage.error('拒绝操作失败，请重试')
    }
  }).catch(() => {})
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadProjectList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  currentPage.value = 1
  loadProjectList()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadProjectList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadProjectList()
}

// 页面加载时获取项目列表
onMounted(() => {
  loadProjectList()
})
</script>

<style scoped lang="scss">
.admin-projects {
  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .project-name {
    display: flex;
    align-items: center;
    gap: 12px;

    .project-cover {
      width: 60px;
      height: 40px;
      border-radius: 4px;
    }
  }

  .detail-cover {
    width: 300px;
    height: 200px;
    border-radius: 4px;
  }
}
</style> 